<?php
/**
 * Created by PhpStorm.
 * User: Rick
 * Date: 2020/12/15
 * Time: 21:19
 * 采集扩展类
 */
class Collect
{
    private $url = null;

    public function __construct($url)
    {
        $this->url = $url;
    }
    public function get_curl()
    {
        $header = array(
            'Accept: application/json',
        );
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $this->url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //执行命令
        $data = curl_exec($curl);
        return $data;
    }

    /**
     * 采集数据
     * @return mixed
     */
    public function collect()
    {
        $get_curl  = $this->get_curl();
        $dom  = new \DOMDocument();
        @$dom->loadHTML($get_curl);
        $data['name'] = $dom->getElementsByTagName('h2')->item(0)->nodeValue;
        $data['director'] = $dom->getElementsByTagName('ul')->item(4)->getElementsByTagName('li')->item(1)->getElementsByTagName('span')->item(0)->nodeValue;
        $data['performer'] = $dom->getElementsByTagName('ul')->item(4)->getElementsByTagName('li')->item(2)->getElementsByTagName('span')->item(0)->nodeValue;
        $data['type_name'] = $dom->getElementsByTagName('ul')->item(4)->getElementsByTagName('li')->item(3)->getElementsByTagName('span')->item(0)->nodeValue;
        $data['desc'] = $dom->getElementsByTagName('span')->item(15)->getAttribute('txt');
        $data['img'] = $dom->getElementsByTagName('img')->item(1)->getAttribute('src');
        $data['url'] = $dom->getElementById('down_1')->getElementsByTagName('input')->item(0)->getAttribute('value');
        $data['img'] = $this->download($data['img'],'.png');
        return $data;
    }

    /**
     * 下载文件
     * @param $fileUrl
     * @param $extend
     * @return bool|int
     */
    public function download($fileUrl,$extend = '.txt')
    {
        $file_name = md5(rand(00000,99999)).$extend;
        $dir = public_path('storage/uploads/').$file_name;
        if (!file_exists($dir)){
            $file = file_get_contents($fileUrl);
            $file_route = file_put_contents($dir,$file);
            if ($file_route){
                return $file_name;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

}